package net.qiqbframework.eventhandling;


import net.qiqbframework.config.ConfigurationException;
import net.qiqbframework.messaging.Message;
import net.qiqbframework.messaging.annotation.MessageExecutableHandler;
import net.qiqbframework.messaging.annotation.ExecutableHandlerWrapper;
import net.qiqbframework.messaging.annotation.WrappedMessageExecutableHandler;

import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;

public class MethodEventExecutableHandler implements ExecutableHandlerWrapper {

    @Override
    public MessageExecutableHandler wrap(@Nonnull MessageExecutableHandler original) {

        return original.annotationAttributes(EventHandler.class)
                .map(attr -> (MessageExecutableHandler) new EventMessageExecutableHandlerImpl(original, attr))
                .orElse(original);
    }

    private static class EventMessageExecutableHandlerImpl extends WrappedMessageExecutableHandler implements EventExecutableHandler {

        private final boolean broadcast;

        private final String handlerDeclaration;

        private EventMessageExecutableHandlerImpl(MessageExecutableHandler delegate, Map<String, Object> annotationAttributes) {
            super(delegate);
            // 获取返回值，
            final Optional<Method> originalMethodOptional = delegate.unwrap(Method.class);
            if (originalMethodOptional.isEmpty()) {
                throw new ConfigurationException("找不到方法");
            }
            broadcast = (boolean) annotationAttributes.get("broadcast");
            final Method method = originalMethodOptional.get();
            handlerDeclaration = method.toGenericString();
        }

        @Override
        public boolean canHandle(@Nonnull Message<?> message) {
            if (message instanceof EventMessage<?> eventMessage) {
                if (super.canHandle(message)) {
                    // 探子直接过
                    if (eventMessage.isScout()) {
                        return true;
                    }
                    return true;// eventMessage.supportHandlerUrl() != null && eventMessage.supportHandlerUrl().contains(handlerDeclaration);
                }
            }
            return false;

        }

        @Override
        public Object handle(@Nonnull Message<?> message, Object target) throws Exception {

            return super.handle(message, target);
        }

        @Override
        public boolean broadcast() {
            return broadcast;
        }

        @Override
        public String handlerDeclaration() {
            return handlerDeclaration;
        }
    }
}
